import 'dart:async';
import 'dart:math';

import 'package:demo_map/map_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_compass/flutter_compass.dart';
import 'package:get/get_state_manager/src/simple/get_state.dart';
import 'package:get/instance_manager.dart';
import 'package:latlong2/latlong.dart';

class MapTab extends StatefulWidget {
  const MapTab({super.key});

  @override
  State<MapTab> createState() => _MapTabState();
}

class _MapTabState extends State<MapTab> with SingleTickerProviderStateMixin {
  final MarkerController _markerController = Get.put(MarkerController()); // 新增
  late final MapController _mapController;
  final LatLng _currentPosition = const LatLng(39.916527, 116.397128);
  StreamSubscription<CompassEvent>? _compassSub;
  late AnimationController _controller;
  late Animation<double> _animation;
  var zoom = 17.0;

  @override
  void initState() {
    super.initState();
    try {
      _mapController = MapController();
      _getCompass(); //罗盘启动
      // 初始化时计算GIF图的大小并赋值
      double pixelSize = calculatePixelSizeForArea(zoom, 1.0 /*平方公里*/);
      _markerController.updateGifSize(pixelSize, pixelSize);

      // 使用flutter提供的动画控制器🔽
      // _controller = AnimationController(
      //   duration: const Duration(milliseconds: 1000),
      //   vsync: this,
      // )..repeat(reverse: true);

      // _animation = Tween<double>(begin: 0.0, end: 1.0).animate(_controller);
      // 使用flutter提供的动画控制器🔼
    } catch (e) {
      print('初始化错误: $e');
    }
  }

  // 获取罗盘角度
  var _lastjaodu = 0;
  Future<void> _getCompass() async {
    try {
      FlutterCompass.events!.listen(
        (event) {
          if (event.heading == null) {
            // 提示用户校准设备
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('指南针传感器不可靠，请校准设备')),
            );
            return;
          }
          // 判断上一个角度和当前角度的差值是否大于2，如果大于1，就更新角度
          final currentHeading = event.heading?.toInt() ?? 0;
          if (event.heading! - _lastjaodu > 2 ||
              event.heading! - _lastjaodu < -2) {
            _markerController.updateHeading(event.heading! * (pi / 180)); // 修改
            _lastjaodu = currentHeading;
          }
        },
        cancelOnError: true,
        onDone: () {
          print('罗盘完成了');
          Timer(const Duration(seconds: 10), _getCompass);
        },
        onError: (e) {
          print('罗盘报错了');
          print(e);
          Timer(const Duration(seconds: 10), _getCompass);
        },
      );
    } catch (e) {
      print('罗盘报错了');
    }
  }

  @override
  void dispose() {
    _compassSub?.cancel();
    _mapController.dispose();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _currentPosition == null
          ? const Center(child: CircularProgressIndicator())
          : FlutterMap(
              // 光这个地图组件展示出来就要4.5%-6.5%
              mapController: _mapController,
              options: MapOptions(
                center: _currentPosition!,
                zoom: zoom,
                maxZoom: 18.0,
                minZoom: 3,
                interactiveFlags:
                    InteractiveFlag.pinchZoom | InteractiveFlag.drag,
                keepAlive: true,
                onPositionChanged: (MapPosition position, bool hasGesture) {
                  if (hasGesture) {
                    if (zoom != position.zoom) {
                      if ((zoom - _mapController.zoom).abs() >= 0.5) {
                        double pixelSize = calculatePixelSizeForArea(
                            _mapController.zoom, 3.0 /*平方公里*/);
                        _markerController.updateGifSize(pixelSize, pixelSize);
                      }
                    }
                  }
                },
              ),
              children: [
                TileLayer(
                  urlTemplate:
                      'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                ),
                GetBuilder<MarkerController>(
                    id: 'gifSize', // 指定一个唯一的id
                    builder: (controller) {
                      return MarkerLayer(
                        markers: [
                          Marker(
                            width: controller.gifWidth,
                            height: controller.gifHeight,
                            point: _currentPosition!,
                            builder: (ctx) {
                              return Image.asset(
                                'assets/images/green.png',
                                width: controller.gifWidth,
                                height: controller.gifHeight,
                                fit: BoxFit.cover,
                                gaplessPlayback: true,
                              );
                            },
                          ),
                        ],
                      );
                    }),
                // 定位图标
                GetBuilder<MarkerController>(
                  id: 'heading',
                  builder: (controller) {
                    return MarkerLayer(
                      markers: [
                        Marker(
                          width: 32,
                          height: 50,
                          point: _currentPosition!,
                          builder: (ctx) => Transform.rotate(
                            angle: controller.heading,
                            child: Image.asset(
                              'assets/images/tower_phone.png',
                              fit: BoxFit.fill,
                              width: 32,
                              height: 50,
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),

                // 圆圈动画  加上这个动画cpu占用率40%左右
                // AnimatedBuilder(
                //   animation: _animation,
                //   builder: (context, child) {
                //     return CircleLayer(
                //       circles: [
                //         CircleMarker(
                //           point: const LatLng(39.916527, 116.397128),
                //           radius: 50,
                //           useRadiusInMeter: true,
                //           color: Color.fromARGB(
                //               (_animation.value * 52).toInt(), 2, 185, 142),
                //           borderStrokeWidth: 0.5,
                //           borderColor: Color.fromARGB(
                //               (_animation.value * 100).toInt(), 2, 185, 142),
                //         ),
                //       ],
                //     );
                //   },
                // ),
                // 定位悬浮按钮
                Positioned(
                  bottom: 16,
                  right: 16,
                  child: FloatingActionButton(
                    onPressed: () {
                      _mapController.move(_currentPosition!, 17.0);
                    },
                    child: const Icon(Icons.my_location),
                  ),
                ),
              ],
            ),
    );
  }

  double calculatePixelSizeForArea(double zoom, double areaInSquareKilometers) {
    // 在墨卡托投影中，地球半径大约是6378137米
    double earthRadius = 6378137;
    // 计算当前缩放级别下，1像素对应的实际距离（以米为单位）
    double circumference = 2 * pi * earthRadius;
    double metersPerPixel = circumference / (256 * pow(2, zoom));
    // 计算覆盖指定面积所需的像素尺寸
    double sideLengthInMeters = sqrt(areaInSquareKilometers * 1000 * 1000);
    double pixelSize = sideLengthInMeters / metersPerPixel;
    return pixelSize;
  }
}
